"use strict";

// #! /usr/bin/env node
/**
 * @env node
 */
const fs = require("node:fs");
const path = require("node:path");
const readline = require("node:readline/promises");

/** @type {Map<string,fs.WriteStream>} */
const fileMap = new Map();

/**
 * @param {string} t
 * @returns {[data: string, time: string]}
 */
const patternData = (t) => {
  const dataReg = /\[(\d+\/\w+\/\d+):(.*?)\]/g;
  const p = t.matchAll(dataReg);
  const pv = p.next();
  if (!pv.value) {
    return ["", ""];
  }
  /**
   * @as {[string, string, string]}
   */
  const pat = pv.value;
  // console.log("pat", pat);
  const [, data, time] = pat;
  // pat.slice(1, 3);
  return [data, time];
};

// 文件名
const sourceFileName = "./access-back-v1.log";

// 创建可读流
const readFileStream = fs.createReadStream(sourceFileName);

// 创建readline接口对象
const rl = readline.createInterface({
  input: readFileStream,
  crlfDelay: Infinity,
});
const interval = global.setInterval(() => {
  const d = new Date();
  console.log(
    `Process >>${d.getHours().toString().padStart(2, "0")}:${d
      .getMinutes()
      .toString()
      .padStart(2, "0")}:${d.getSeconds().toString().padStart(2, "0")}`,
  );
}, 1000);
/**
 * @type {string}
 */
let gcHappyLast = "";
// 逐行读取文件内容并进行处理
rl.on("line", (line) => {
  if (!line.trim()) {
    return;
  }
  const [dateKey] = patternData(line);
  if (!dateKey) {
    return;
  }
  const dateDate = new Date(dateKey);
  const prettyData = `${dateDate.getFullYear()}-${(dateDate.getMonth() + 1)
    .toString()
    .padStart(2, "0")}-${dateDate.getDate().toString().padStart(2, "0")}`;
  if (fileMap.has(prettyData)) {
    gcHappyLast = prettyData;
    const fh = fileMap.get(prettyData);
    if (!fh) {
      return;
    }
    fh.write(`${line}\n`);
  } else {
    if (gcHappyLast !== "" && gcHappyLast !== prettyData) {
      // do free
      fileMap.delete(gcHappyLast);
    }
    fileMap.set(
      prettyData,
      fs.createWriteStream(
        path.join(__dirname, `./well-log/log-${prettyData}.log`),
      ),
    );
  }
});

rl.on("close", () => {
  clearInterval(interval);
  console.log("文件读取完毕");
});
